<template>
  <div class="single-unit-asset-list-wrap">
    <el-row type="flex" justify="space-between">
      <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
        <el-form-item>
          <div class="iconfont icon-return return-btn" @click="returnFun" title="返回">返回建筑物视图</div>
        </el-form-item>
        <el-form-item>
          <tree-select
            placeholder="请选择资产类别"
            v-model="searchForm.categoryIds"
            filterable
            :width="200"
            :data="typeList"
            :defaultProps="typeDefaultProps"
            :checkedKeys="defaultCheckedCategoryId"
            :nodeKey="typeNodeKey"
          ></tree-select>
        </el-form-item>
        <el-form-item>
          <tree-select
            placeholder="请选择建筑物"
            v-model="searchForm.fbsIds"
            filterable
            :width="200"
            :data="buildList"
            :defaultProps="buildDefaultProps"
            :checkedKeys="defaultCheckedFbsId"
            :nodeKey="buildNodeKey"
            @node-click="handleNodeClick"
          ></tree-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable @change="search" placeholder="请选择标识类型" v-model="searchForm.visualCodeType">
            <el-option label="全部标识类型" value="-1"></el-option>
            <el-option label="区域型" value="2"></el-option>
            <el-option label="单点型" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable @change="search" placeholder="请选择质保状态" v-model="searchForm.isOverdue">
            <el-option label="全部质保状态" value="0"></el-option>
            <el-option label="过期" value="1"></el-option>
            <el-option label="未过期" value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态：">
          <el-select @change="search" v-model="searchForm.isUse" placeholder="请选择">
            <el-option label="全部" value="-1"></el-option>
            <el-option label="在用" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-input placeholder="请输入资产名称" v-model="searchForm.name" @keyup.enter.native="search" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="more-btns">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">更多操作</span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="add">新增</el-dropdown-item>
            <el-dropdown-item command="batchAdd">批量新增</el-dropdown-item>
            <el-dropdown-item command="import">批量导入</el-dropdown-item>
            <el-dropdown-item command="export">按当前条件导出</el-dropdown-item>
            <el-dropdown-item command="batchDeletion">批量删除</el-dropdown-item>
            <el-dropdown-item command="modifying">批量修改</el-dropdown-item>
            <!-- <el-dropdown-item command="maintain">维保公司维护</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-row>
    <el-row class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
      <el-col :span="8">
        <div class="item-wrap" @click="searchForm.isUse = -1" :class="searchForm.isUse == -1 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-4">{{ assetStatistics.isUse + assetStatistics.noUse }}</p>
            <p class="item-title">资产总数（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="item-wrap" @click="searchForm.isUse = 0" :class="searchForm.isUse == 0 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-3">{{ assetStatistics.isUse }}</p>
            <p class="item-title">在用资产（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="item-wrap" @click="searchForm.isUse = 1" :class="searchForm.isUse == 1 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-1">{{ assetStatistics.noUse }}</p>
            <p class="item-title">停用资产（个）</p>
          </div>
        </div>
      </el-col>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        ref="singleUnitTableList"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="现场图片" prop="picturesUrls" width="120">
          <template slot-scope="scope">
            <img
              :src="
                scope.row.picturesUrls
                  ? scope.row.picturesUrls.split(',')[0]
                  : defaultImg
              "
              width="50"
              height="50"
              @click="$imgPreview"
              :data-imgpreview="scope.row.picturesUrls"
            />
          </template>
          <!-- <template v-if="scope.row.picturesUrls != ''" slot-scope="scope">
            <img :src="scope.row.picturesUrls.split(',')[0]" width="50px" height="50px" @click="$imgPreview" :data-imgpreview="scope.row.picturesUrls">
          </template>-->
        </el-table-column>
        <el-table-column label="消防系统" prop="fireSystemName" width="200"></el-table-column>
        <el-table-column label="资产类别" prop="categoryName" width="200"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 0" class="type-tags type-color-3">在用</div>
            <div v-else class="type-tags type-color-1">停用</div>
          </template>
        </el-table-column>
        <el-table-column label="位置" prop="locationDetail" width="350">
          <template slot-scope="scope">
            <el-link type="primary" @click="openPosition(scope.row)">
              {{
              scope.row.locationDetail
              }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="标识类型" prop="visualCodeType" width="200">
          <!-- 0：单点自动 1：单点手动 2:区域 -->
          <template slot-scope="scope">
            <p v-if="
                scope.row.visualCodeType == 0 || scope.row.visualCodeType == 1
              ">单点型</p>
            <p v-else>区域型</p>
          </template>
        </el-table-column>
        <el-table-column label="质保状态" prop="isExpire" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.isExpire === 1">过期</div>
            <div v-else>未过期</div>
          </template>
        </el-table-column>
        <el-table-column label="二维码" prop="visualCode" width="100">
          <template slot-scope="scope">
            <template v-if="scope.row.visualCode">
              <el-popover placement="top" width="320" trigger="hover">
                <div class="qr-hover-wrap">
                  <vue-qr :text="scope.row.visualCode || ''" :size="200" :dotScale="1"></vue-qr>
                  <p class="qr-code-text">{{ scope.row.visualCode }}</p>
                </div>
                <vue-qr slot="reference" :text="scope.row.visualCode || ''" :size="50" :margin="0" :dotScale="0.75"></vue-qr>
              </el-popover>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="handleDetail(scope.row)" type="text" size="small">详情</el-button>
            <span class="dividing-line">|</span>
            <el-button @click="editAssetInfo(scope.row)" type="text" size="small">编辑</el-button>
            <span class="dividing-line">|</span>
            <el-button @click="deleteUser(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column type="expand" width="1">
          <template slot-scope="scope">
            <el-tabs type="border-card" v-model="defaultTabsName[scope.row.id]">
              <el-tab-pane name="maintenanceRecord">
                <span slot="label">维保记录</span>
                <div
                  class="maintenance-record-wrap block"
                  v-if="
                    maintainRecords['maintainRecords_' + scope.row.id] &&
                      maintainRecords['maintainRecords_' + scope.row.id]
                        .length > 0
                  "
                >
                  <el-timeline>
                    <el-timeline-item
                      v-for="(item, index) in maintainRecords[
                        'maintainRecords_' + scope.row.id
                      ]"
                      :key="index"
                      :timestamp="item.startTime"
                      hide-timestamp
                    >
                      <!-- 区域型资产维保记录 -->
                      <template v-if="item.businessType == 2">
                        <p>{{ mapMaintainType(item.maintainType) }}</p>
                        <p>{{ item.startTime }}</p>
                        <el-card>
                          <p>
                            关联任务：
                            <span>{{ item.taskName }}</span>
                          </p>
                          <p>
                            维保人员：
                            <span>{{ item.maintainName }}</span>
                          </p>
                        </el-card>
                      </template>
                      <!-- 单点型资产维保记录 -->
                      <template v-else>
                        <p>{{ mapMaintainType(item.maintainType) }}</p>
                        <p>{{ item.updateTime }}</p>
                        <el-card>
                          <el-row>
                            <el-col :span="12">
                              <p>作业填报</p>
                              <el-row>
                                <el-col
                                  v-for="(obj,
                                  i) in item.maintainStandardContent"
                                  :key="obj.id"
                                  :span="24"
                                  class="work-item"
                                >
                                  <p>
                                    <span class="maintain-standard-index">
                                      {{
                                      i + 1
                                      }}
                                    </span>
                                    {{ obj.workContent }}
                                  </p>
                                  <!-- 工作结果类型分类 -->
                                  <p v-if="obj.type == 1" class="maintain-standard-result">
                                    工作结果：{{
                                    maintainStandardResultMap(obj.result.tab)
                                    }}
                                  </p>
                                  <p
                                    v-else-if="obj.type == 2"
                                    class="maintain-standard-result"
                                  >工作结果：{{ obj.result.des }}</p>
                                  <p
                                    v-else-if="obj.type == 3"
                                    class="maintain-standard-result"
                                  >工作结果：{{ obj.result.num }}</p>
                                  <p v-else-if="obj.type == 4" class="maintain-standard-result">
                                    工作结果：{{
                                    maintainStandardResultMap(obj.result.tab)
                                    }}&nbsp;&nbsp;{{ obj.result.des }}
                                  </p>
                                  <p v-else-if="obj.type == 5" class="maintain-standard-result">
                                    工作结果：{{
                                    maintainStandardResultMap(obj.result.tab)
                                    }}&nbsp;&nbsp;{{ obj.result.num }}
                                  </p>
                                  <p v-else-if="obj.type == 6" class="maintain-standard-result">
                                    工作结果：{{ obj.result.des }}&nbsp;&nbsp;{{
                                    obj.result.num
                                    }}
                                  </p>
                                </el-col>
                              </el-row>
                            </el-col>
                            <el-col :span="12">
                              <div>
                                <p>作业前照片</p>
                                <div class="img-wrap">
                                  <div v-if="item.picBeforeUrls">
                                    <img
                                      v-for="obj in item.picBeforeUrls.split(
                                        ','
                                      )"
                                      :key="obj"
                                      :src="obj"
                                      @click="$imgPreview"
                                      :data-imgpreview="item.picBeforeUrls"
                                    />
                                  </div>
                                  <div v-else style="margin-bottom: 10px; color: #888">暂无作业前照片</div>
                                </div>
                              </div>
                              <p>作业后照片</p>
                              <div class="img-wrap">
                                <div v-if="item.picAfterUrls">
                                  <img
                                    v-for="obj in item.picAfterUrls.split(',')"
                                    :key="obj"
                                    :src="obj"
                                    @click="$imgPreview"
                                    :data-imgpreview="item.picAfterUrls"
                                  />
                                </div>
                                <div v-else style="margin-bottom: 10px; color: #888">暂无作业后照片</div>
                              </div>
                            </el-col>
                          </el-row>
                          <p>
                            关联任务：
                            <span>{{ item.taskName }}</span>
                          </p>
                          <p>
                            维保人员：
                            <span>{{ item.maintainName }}</span>
                          </p>
                        </el-card>
                      </template>
                    </el-timeline-item>
                  </el-timeline>
                  <el-button
                    type="primary"
                    v-if="
                      maintainRecordsPageIndex[
                        'maintainRecords_' + scope.row.id
                      ].currentPageIndex <
                        Math.ceil(
                          maintainRecordsPageIndex[
                            'maintainRecords_' + scope.row.id
                          ].total / 5
                        ) -
                          1
                    "
                    @click="
                      getMaintainRecordsByAssetsId(
                        maintainRecordsPageIndex[
                          'maintainRecords_' + scope.row.id
                        ].currentPageIndex + 1,
                        scope.row.id
                      )
                    "
                  >查看更多</el-button>
                </div>
                <div v-else>暂无维保记录</div>
              </el-tab-pane>
              <el-tab-pane name="fixRecord">
                <span slot="label">故障维修记录</span>
                <div v-if="brokenRecords['brokenRecords_' + scope.row.id]">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(item, index) in brokenRecords[
                        'brokenRecords_' + scope.row.id
                      ]"
                      :key="index"
                      :timestamp="item.createTime"
                      hide-timestamp
                    >
                      <div class="broken-record-wrap">
                        <p>{{ item.createTime }}</p>
                        <p>{{ item.status == 1 ? "整改中" : "已完成" }}</p>
                        <p v-if="item.picUrls !== ''">
                          <img
                            class
                            v-for="(obj, index) in item.picUrls.split(',')"
                            :key="index"
                            :src="obj"
                            @click="$imgPreview"
                            :data-imgpreview="item.picUrls"
                          />
                        </p>
                        <p>{{ item.hiddenDangerDesc }}</p>
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                  <el-button
                    type="primary"
                    v-if="
                      brokenRecordsPageIndex['brokenRecords_' + scope.row.id]
                        .currentPageIndex <
                        Math.ceil(
                          brokenRecordsPageIndex[
                            'brokenRecords_' + scope.row.id
                          ].total / 5
                        ) -
                          1
                    "
                    @click="
                      getAssetsMaintenanceList(
                        brokenRecordsPageIndex['brokenRecords_' + scope.row.id]
                          .currentPageIndex + 1,
                        scope.row.id
                      )
                    "
                  >查看更多</el-button>
                </div>
                <div v-else>暂无维修记录</div>
              </el-tab-pane>
              <el-tab-pane name="baseInfo">
                <span slot="label">更多信息</span>
                <el-form v-if="assetInfos[scope.row.id]" label-width="120px" class="demo-table-expand">
                  <el-form-item label="编号">
                    <span>{{ assetInfos[scope.row.id].serialNumber }}</span>
                  </el-form-item>
                  <el-form-item label="型号">
                    <span>{{ assetInfos[scope.row.id].model }}</span>
                  </el-form-item>
                  <el-form-item label="品牌">
                    <span>{{ assetInfos[scope.row.id].brand }}</span>
                  </el-form-item>
                  <el-form-item label="生产厂家">
                    <span>{{ assetInfos[scope.row.id].producerName }}</span>
                  </el-form-item>
                  <el-form-item label="生产日期">
                    <span>{{ (assetInfos[scope.row.id].productionTime||'').substr(0,10) }}</span>
                  </el-form-item>
                  <el-form-item label="过期时间">
                    <span>{{ (assetInfos[scope.row.id].expireDate||'').substr(0,10) }}</span>
                  </el-form-item>
                  <el-form-item label="维保公司">
                    <span>
                      {{
                      assetInfos[scope.row.id].maintenanceCompanyName
                      }}
                    </span>
                  </el-form-item>
                  <el-form-item label="关联物联设备">
                    <span>{{ assetInfos[scope.row.id].relateFcNames }}</span>
                  </el-form-item>
                  <el-form-item label="入库时间">
                    <span>
                      {{
                      formatDateTime(assetInfos[scope.row.id].createTime)
                      }}
                    </span>
                  </el-form-item>
                  <el-form-item label="备注">
                    <span>{{ assetInfos[scope.row.id].remarks }}</span>
                  </el-form-item>
                </el-form>
                <p v-else style="text-align: center;">暂无信息</p>
              </el-tab-pane>
            </el-tabs>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 新增/编辑资产弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      width="600px"
      top="0vh"
      v-if="dialogBaseInfo"
      :visible.sync="dialogBaseInfo"
      @close="closeAssetInfo"
      v-dialogDrag
      id="isProperty"
    >
      <asset-info-form
        :organizationId="organizationId"
        :assetInfo="assetInfo"
        :closeAssetInfo="closeAssetInfo"
        :onUpdata="onUpdata"
        :typeList="typeList"
        :buildList="buildList"
        :isAddWrite="isAddWrite"
        :defaultFbsId="isChooseTree?'':searchForm.fbsIds"
        @child-event="parentEvent"
      ></asset-info-form>
    </el-dialog>
    <!-- 批量新增 -->
    <el-dialog
      v-if="showBatchAdd"
      :close-on-click-modal="false"
      title="批量新增资产"
      :top="dialogLarger?'0':'10vh'"
      :width="dialogLarger?'1600px':'800px'"
      :visible.sync="showBatchAdd"
      @close="closeBatchAdd"
      v-dialogDrag
      :custom-class="dialogLarger?'dialog-full-height':''"
    >
      <batch-add
        :organizationId="organizationId"
        :buildList="buildList"
        @refresh-list="closeBatchAdd();search();"
        @larger="onBatchStarted"
      ></batch-add>
    </el-dialog>
    <!-- 导入资产 -->
    <el-dialog
      :close-on-click-modal="false"
      title="批量导入资产"
      width="600px"
      top="10vh"
      v-if="dialogImportAsset"
      :visible.sync="dialogImportAsset"
      @close="closeImportAsset"
      v-dialogDrag
    >
      <import-asset :organizationId="organizationId" :close="closeImportAsset"></import-asset>
    </el-dialog>
    <!-- 批量修改 -->
    <el-dialog
      :close-on-click-modal="false"
      title="批量修改"
      width="600px"
      top="10vh"
      v-if="dialogBatchModifying"
      :visible.sync="dialogBatchModifying"
      @close="closeModifyingAsset"
      v-dialogDrag
    >
      <batch-modifying
        :organizationId="organizationId"
        :closeModifyingAsset="closeModifyingAsset"
        :multipleSelection="multipleSelection"
      ></batch-modifying>
    </el-dialog>
    <!-- 维保公司维护弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="维保公司维护"
      width="600px"
      top="25vh"
      :visible.sync="dialogMaintenanceCompany"
      @close="dialogMaintenanceCompany = false"
      v-dialogDrag
    >
      <el-table :data="maintenanceCompanyList" style="width: 100%">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="维保公司名称" prop="name"></el-table-column>
      </el-table>
      <el-form class="add-co-form" :inline="true" @submit.native.prevent>
        <el-form-item class="company-name-input">
          <el-input
            placeholder="请输入新的维保公司"
            v-model="newMaintenanceCompanyName"
            @keyup.enter.native="addMaintenanceCompany"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addMaintenanceCompany">添加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 位置 -->
    <multifunction-dialog v-if="dialogLocaltion" :parames="multifunctionDialogparames" @close="dialogLocaltion = false"></multifunction-dialog>
  </div>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import * as Dao from '@/api/assets'
import assetInfoForm from '../Dialog/AssetInfoForm'
import importAsset from '../Dialog/ImportAsset'
import batchModifying from '../Dialog/BatchModifying'
import utils from '@/utils/util'
import MultifunctionDialog from '../../MultifunctionDialog/Main'
import BatchAdd from '../Dialog/BatchAdd'
import { debug } from 'util'
export default {
  name: 'SingleUnitAssetList',
  components: {
    TreeSelect,
    assetInfoForm,
    importAsset,
    MultifunctionDialog,
    batchModifying,
    BatchAdd,
  },
  props: {
    // 页面跳转附带的参数
    queryObj: {
      type: Object,
      default() {
        return {}
      },
    },
    organizationId: {
      required: true,
    },
    organizationName: {
      default() {
        return ''
      },
    },
    // hasFather: {
    //   type: Boolean,
    //   default () {
    //     return false
    //   }
    // },
    returnFun: {
      type: Function,
      default() {
        return () => {}
      },
    },
  },
  data() {
    return {
      dialogLarger: false,
      loading: true,
      dialogBaseInfo: false,
      dialogTitle: '新增资产',
      dialogMaintenanceCompany: false,
      dialogImportAsset: false,
      dialogBatchModifying: false,
      dialogLocaltion: false,
      defaultImg: this.GLOBAL.defaultImg,
      multifunctionDialogparames: {},
      searchForm: {
        categoryIds: '', // 消防系统树结构
        fbsIds: this.queryObj && this.queryObj.fbsId ? this.queryObj.fbsId : '', // 建筑物结构
        isUse: '-1', // 状态
        visualCodeType: '-1', // 标识类型
        isOverdue: '0', // 是否过期
        name: '', // 名称
      },
      // 消防系统-资产类别
      typeList: [],
      typeDefaultProps: {
        children: 'categoryList',
        label: 'name',
        value: 'id',
      },
      typeNodeKey: 'id',
      defaultCheckedCategoryId: [],
      // 建筑物
      buildList: [],
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedFbsId: [],
      // 状态
      statusList: [],
      // 列表
      tableData: [],
      //被选中的行
      multipleSelection: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      assetStatistics: {
        isUse: 0,
        noUse: 0,
      }, // 资产统计信息
      assetInfos: {}, // 资产详细信息
      // maintenanceRecord: [], // 维保记录
      fixRecord: [], // 故障维修记录
      defaultTabsName: {},
      // 维保公司列表
      maintenanceCompanyList: [],
      newMaintenanceCompanyName: '',
      // 维保记录详情集合
      maintainRecords: {},
      maintainRecordsPageIndex: {},
      // 故障维修记录详情集合
      brokenRecords: {},
      brokenRecordsPageIndex: {},
      isAddWrite: false,
      scrollTop: 0,
      timer: null,
      showBatchAdd: false,
      isChooseTree: false,
    }
  },
  created() {
    let that = this
    // 是否是页面跳转
    if (that.queryObj.orgId) {
      that.organizationId = that.queryObj.orgId
    }
    if (that.queryObj.name) {
      that.searchForm.name = that.queryObj.name
    }
    this.init()
  },
  methods: {
    handleNodeClick(val) {
      if (val.type == 4 || val.type == 5) {
        this.isChooseTree = false
      } else {
        this.isChooseTree = true
      }
    },
    onBatchStarted() {
      this.dialogLarger = true
    },
    init() {
      this.getTypeList()
      this.getBuildList()
      // 获取统计信息
      this.getAssetCount()
      this.getTableData()
    },
    // 利用计时器让弹框返回顶部
    parentEvent(data) {
      if (data) {
        this.scrollTop = document.getElementById('isProperty').scrollTop
        this.timer = setInterval(() => {
          this.scrollToTopTimer()
        }, 10)
      }
    },
    scrollToTopTimer() {
      if (document.getElementById('isProperty').scrollTop > 0) {
        document.getElementById('isProperty').scrollTop -= 10
      } else if (document.getElementById('isProperty').scrollTop <= 0) {
        clearInterval(this.timer)
      }
    },
    getTypeList() {
      let that = this
      Dao.getAssetsCategoryIdWithAssets({
        orgId: that.organizationId,
      }).then((res) => {
        // 加上全部
        res.data.unshift({
          id: '',
          name: '全部资产类别',
        })
        that.typeList = res.data
        // 默认选择全部
        that.$nextTick(() => {
          that.defaultCheckedCategoryId = ['']
        })
      })
    },
    getBuildList() {
      let that = this
      Dao.getFbsTree({
        organizationId: that.organizationId,
      }).then((res) => {
        that.buildList = res.data.length === 0 ? [] : res.data
        that.$nextTick(() => {
          if (that.queryObj && that.queryObj.fbsId) {
            // 设置所在建筑物下拉框初始值
            that.defaultCheckedFbsId = String(that.queryObj.fbsId).split(',')
          } else {
            that.defaultCheckedFbsId = ['']
          }
        })
      })
    },
    // 获取多业主单位的统计信息
    getAssetCount() {
      let that = this
      let parames = {
        queryType: 0,
        organizationId: this.organizationId || '',
        name: that.searchForm.name.trim(),
        categoryIds: that.searchForm.categoryIds || '',
        fbsIds: that.searchForm.fbsIds || '',
        visualCodeType: that.searchForm.visualCodeType,
        isOverdue: that.searchForm.isOverdue || 0,
      }
      Dao.getAListForPcStatusCount(parames).then((res) => {
        this.assetStatistics.isUse = res.data.inUse
        this.assetStatistics.noUse = res.data.noUse
      })
    },
    // 获取列表数据
    getTableData(pageIndex, pageSize, isUse) {
      let that = this
      that.loading = true
      if (pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      let parames = {
        queryType: 1,
        organizationId: that.organizationId,
        name: that.searchForm.name.trim(),
        categoryIds: that.searchForm.categoryIds || '',
        fbsIds: that.searchForm.fbsIds || '',
        isUse: that.searchForm.isUse,
        visualCodeType: that.searchForm.visualCodeType,
        isOverdue: that.searchForm.isOverdue || 0,
        pageSize: that.pageSize,
        pageIndex: that.currentPage - 1,
      }
      // 获取列表信息
      Dao.getAListForPc(parames).then((res) => {
        that.tableData = res.data
        // 初始化详情记录
        that.maintainRecords = {}
        that.total = res.total
        that.loading = false
      })
    },
    handleSizeChange(pageSize) {
      this.getTableData(1, pageSize, true)
    },
    handleCurrentChange(currentPage) {
      this.getTableData(currentPage, this.pageSize, true)
    },
    formatDateTime: function (value) {
      return utils.ilinkTimeformat.format(
        new Date(value),
        'yyyy-MM-dd hh:mm:ss'
      )
    },
    // 查询
    search() {
      this.getAssetCount()
      this.getTableData(1)
    },
    // 打开显示位置弹框
    openPosition(row) {
      let that = this
      that.dialogLocaltion = true
      that.multifunctionDialogparames = {
        name: row.locationDetail,
        fcfId: row.relateFcIds,
      }
    },
    closeAssetInfo(refresh) {
      this.dialogBaseInfo = false
      clearInterval(this.timer)
      if (typeof refresh === 'boolean' && refresh) {
        this.getAssetCount()
        this.getTableData(this.assetInfo.id ? '' : 1)
      }
    },
    onUpdata() {
      this.search()
    },
    closeModifyingAsset(refresh) {
      this.dialogBatchModifying = false
      if (typeof refresh === 'boolean' && refresh) {
        this.currentPage = 0
        this.search()
      }
    },
    // 维保类型名称映射
    mapMaintainType(code) {
      const TypeMAP = {
        1: '维保巡查',
        2: '保养',
        3: '单点测试',
        4: '联动测试',
      }

      return TypeMAP[code] || ''
    },
    // 单点型资产维保结果映射
    maintainStandardResultMap(code) {
      const ResultMAP = {
        0: '正常',
        1: '异常',
        2: '未涉及',
      }

      return ResultMAP[code] || ''
    },
    // 详情
    handleDetail(row) {
      let that = this
      if (
        row &&
        !that.maintainRecords.hasOwnProperty('maintainRecords_' + row.id)
      ) {
        // 获取维保记录
        that.getMaintainRecordsByAssetsId(0, row.id)

        // 获取故障维修记录
        that.getAssetsMaintenanceList(0, row.id)

        // 获取更多信息
        Dao.getAInfo({
          id: row.id,
        }).then((res) => {
          that.$set(that.assetInfos, row.id, res.data)
        })
      }
      that.$set(that.defaultTabsName, row.id, 'maintenanceRecord')
      this.$refs.singleUnitTableList.toggleRowExpansion(row)
    },
    // 获取维保记录
    getMaintainRecordsByAssetsId(pageIndex, id) {
      let that = this
      if (
        that.maintainRecordsPageIndex.hasOwnProperty('maintainRecords_' + id)
      ) {
        that.maintainRecordsPageIndex[
          'maintainRecords_' + id
        ].currentPageIndex = pageIndex
      }

      Dao.getMaintainRecordsByAssetsId({
        assetsId: id,
        pageIndex: pageIndex,
        pageSize: 5,
      }).then((res) => {
        if (res.data.length > 0) {
          if (!that.maintainRecords.hasOwnProperty('maintainRecords_' + id)) {
            // 首次加载
            // 分页信息
            that.$set(that.maintainRecordsPageIndex, 'maintainRecords_' + id, {
              currentPageIndex: 0,
              total: res.total,
            })
            // 列表信息
            that.$set(that.maintainRecords, 'maintainRecords_' + id, res.data)
          } else {
            that.maintainRecords[
              'maintainRecords_' + id
            ] = that.maintainRecords['maintainRecords_' + id].concat(res.data)
          }
        } else {
          // 分页信息
          that.$set(that.maintainRecordsPageIndex, 'maintainRecords_' + id, {
            currentPageIndex: 0,
            total: 0,
          })
          // 列表信息
          that.$set(that.maintainRecords, 'maintainRecords_' + id, [])
        }
      })
    },
    // 获取故障维修记录
    getAssetsMaintenanceList(pageIndex, id) {
      let that = this
      if (that.brokenRecordsPageIndex.hasOwnProperty('brokenRecords_' + id)) {
        that.brokenRecordsPageIndex[
          'brokenRecords_' + id
        ].currentPageIndex = pageIndex
      }
      Dao.getAssetsMaintenanceList({
        assetsId: id,
        pageIndex: pageIndex,
        pageSize: 5,
      }).then((res) => {
        if (res.data.length > 0) {
          if (!that.brokenRecords.hasOwnProperty('brokenRecords_' + id)) {
            that.$set(that.brokenRecordsPageIndex, 'brokenRecords_' + id, {
              currentPageIndex: 0,
              total: res.total,
            })
            that.$set(that.brokenRecords, 'brokenRecords_' + id, res.data)
          } else {
            that.brokenRecords['brokenRecords_' + id] = that.brokenRecords[
              'brokenRecords_' + id
            ].concat(res.data)
          }
        }
      })
    },
    // 编辑
    editAssetInfo(row) {
      if (row) {
        this.dialogTitle = '编辑资产'
        // 获取资产详细信息
        Dao.getAInfo({
          id: row.id,
        }).then((res) => {
          this.assetInfo = res.data
          this.isAddWrite = false
          this.dialogBaseInfo = true
        })
      }
    },
    // 删除
    deleteUser(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      if (row) {
        this.$confirm('确认删除该资产吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true,
        })
          .then(() => {
            Dao.delAInfo({ ids: row.id }).then((res) => {
              if (res.status === 200) {
                that.$message({
                  type: 'success',
                  message: '删除成功!',
                })
                setTimeout(() => {
                  this.currentPage = 0
                  that.search()
                }, 1000)
              } else {
                that.$message.error(res.info)
              }
            })
            // 阻止事件冒泡
            event.stopPropagation()
          })
          .catch(() => {})
      }
    },
    // 更多操作
    handleCommand(command) {
      let that = this

      switch (command) {
        case 'add':
          that.addAsset()
          return false
        case 'import':
          that.importList()
          return false
        case 'export':
          that.exportList()
          return false
        case 'batchDeletion':
          that.batchDeletion()
          return false
        case 'modifying':
          that.modifying()
          return false
        case 'batchAdd':
          this.dialogLarger = false
          that.showBatchAdd = true
          return false
        // case 'maintain':
        //   that.maintenanceCompany()
        //   return false
        default:
          return false
      }
    },
    // 新增
    addAsset() {
      this.dialogTitle = '新增资产'
      this.assetInfo = {}
      this.isAddWrite = true
      this.dialogBaseInfo = true
    },
    // 批量导入
    importList() {
      this.dialogImportAsset = true
    },
    closeImportAsset(refresh) {
      this.dialogImportAsset = false
      if (typeof refresh === 'boolean' && refresh) {
        this.search()
      }
    },
    //多选框
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //批量删除
    batchDeletion() {
      let ids = []
      let that = this
      let selectList = this.multipleSelection
      if (selectList.length > 0) {
        // 确认弹框
        this.$confirm('确认删除选中的资产吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true,
        })
          .then(() => {
            for (var i = 0, len = selectList.length; i < len; i++) {
              ids.push(selectList[i].id)
            }
            //删除接口
            Dao.delAInfo({
              ids: ids.toString(),
            }).then((res) => {
              if (res.status === 200) {
                that.$message.success('删除成功!')
                setTimeout(() => {
                  that.search()
                }, 1000)
              }
            })
          })
          .catch(() => {})
      } else {
        that.$message.warning('请勾选你要删除的资产')
      }
    },
    // 批量修改
    modifying() {
      let _this = this
      let selectList = _this.multipleSelection
      if (selectList.length > 0) {
        _this.dialogBatchModifying = true
      } else {
        _this.$message.warning('请勾选你要修改的资产')
      }
    },
    // 按条件导出
    exportList() {
      let that = this
      let downloadUrl =
        this.GLOBAL.baseURL +
        'assets/exportAList?organizationId=' +
        that.organizationId +
        '&name=' +
        that.searchForm.name +
        '&categoryIds=' +
        (that.searchForm.categoryIds || '') +
        '&visualCodeType=' +
        that.searchForm.visualCodeType +
        '&fbsIds=' +
        (that.searchForm.fbsIds || '') +
        '&status=' +
        that.searchForm.isUse +
        '&isOverdue=' +
        that.searchForm.isOverdue
      window.open(downloadUrl)
    },
    // 维保公司维护
    // maintenanceCompany() {
    //     let that = this
    //     Dao.getAMCs({
    //         orgId: that.organizationId
    //     }).then(res => {
    //        that.maintenanceCompanyList = res.data
    //     })
    //     that.newMaintenanceCompanyName = ''
    //     this.dialogMaintenanceCompany = true
    // },
    // 添加新的维保公司
    addMaintenanceCompany() {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      if (that.newMaintenanceCompanyName.trim() !== '') {
        Dao.updateAMC({
          name: that.newMaintenanceCompanyName.trim(),
          organizationId: that.organizationId,
          account: that.$store.state.userinfo.accountName,
        }).then((res) => {
          if (res.status === 200) {
            that.$message({
              type: 'success',
              message: '添加成功',
            })
            setTimeout(() => {
              that.dialogMaintenanceCompany = false
            }, 1000)
          } else {
            that.$message({
              type: 'warning',
              message: res.info,
            })
          }
        })
      } else {
        that.$message({
          type: 'warning',
          message: '请输入维保公司名称',
        })
      }
    },
    closeBatchAdd() {
      this.showBatchAdd = false
    },
  },
  watch: {
    queryObj(val) {
      // 是否是页面跳转
      if (val.orgId) {
        that.organizationId = that.queryObj.orgId
        that.searchForm.name = that.queryObj.name
        this.init()
      }
    },
    categoryIdsSelect(val, oldVal) {
      if (val != null && val !== oldVal) {
        this.search()
      }
    },
    fbsIdsSelect(val, oldVal) {
      if (val && val !== oldVal) {
        this.search()
      }
    },
    isUseSelect(val, oldVal) {
      if (val !== oldVal) {
        this.getTableData(1, false, true)
      }
    },
  },
  computed: {
    categoryIdsSelect() {
      return this.searchForm.categoryIds
    },
    fbsIdsSelect() {
      return this.searchForm.fbsIds
    },
    isUseSelect() {
      return this.searchForm.isUse
    },
  },
  destroyed() {
    clearInterval(this.timer)
  },
}
</script>
<style lang="scss">
.single-unit-asset-list-wrap {
  .el-form-item {
    margin-bottom: 0;
  }
  .add-co-form {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    .company-name-input {
      .el-form-item__content {
        width: 400px;
      }
    }
  }
  .maintenance-record-wrap {
    .img-wrap {
      margin-top: 10px;
      img {
        border: 1px solid #e3e3e3;
        margin-right: 15px;
        width: 60px;
        height: 60px;
      }
    }
    .work-item {
      margin-top: 10px;
      .maintain-standard-index {
        display: inline-block;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        background-color: #205fa9;
        color: #fff;
        border-radius: 50%;
      }
      .maintain-standard-result {
        text-indent: 2em;
      }
    }
  }
  .broken-record-wrap {
    p {
      margin-bottom: 10px;
    }
  }
}
.qr-hover-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  .qr-code-text {
    margin-top: 10px;
  }
}
</style>
